package com.hmkj.admin.controller.account;

import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.utils.PriceHelper;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.po.account.Account;
import com.hmkj.core.po.account.AccountCash;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.service.account.AccountService;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.order.OrderService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping(BaseController.BASE_URI)
public class DiyanJsonController extends GenericController<Integer, Order> {

    @Resource
    private OrderService orderService;
    @Resource
    private AccountService accountService;
    @Resource
    private RedisService redisService;

    /**
     * 递延费不足列表数据
     *
     * @param dtGridPager
     * @return
     */
    @RequestMapping("diyan/list.json")
    @ResponseBody
    @RequiresPermissions("sys:diyan:less:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        dtGridPager = dataAuthority(dtGridPager);
        dtGrid = orderService.getDtGridListForDiyan(dtGridPager, Order.class);
        List<Object> list = dtGrid.getExhibitDatas();
        //  每万元递延费
        BigDecimal diyanFee = redisService.get(ConfigNID.DIYAN_FEE, BigDecimal.class);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Object obj : list) {
                LinkedHashMap model = (LinkedHashMap) obj;
                //查找用户账户余额
                Account account = accountService.selectByUID((int)model.get("userId"));
                //计算全部递延费
                BigDecimal total = BigDecimal.valueOf(Double.parseDouble(model.get("sumTradeCredit").toString())).multiply(diyanFee);
                model.put("lessDiyan",PriceHelper.isLessThan(account.getAvailable(), total) ? total.subtract(account.getAvailable()) : BigDecimal.ZERO);
            }
        }
        return dtGrid;
    }
}
